<template>
	<view>
		<zero-loading type="circle" v-if="loading"></zero-loading>
		<view class="title "></view>
		<scroll-view scroll-y="true" class="scroll-Y" :style='{ height: scrollHeight }'>
			<view class="flex text-center nav">
				<view :class="TabCur==0?'text-olive cur':'text-grey'" class="cu-item  flex-sub  " @tap="onTabSelect(0)">
					<i class="padding-right-xs"></i>
					<text class=" text-md ">
						场区信息
					</text>
				</view>
				<view :class="TabCur==1?'text-olive cur':'text-grey'" class="cu-item flex-sub  " @tap="onTabSelect(1)">
					<i class="padding-right-xs"></i>
					<text class=" text-md ">
						单元列表
					</text>
				</view>
			</view>

			<block v-if="TabCur==0">
				<scroll-view scroll-y="true" class="scroll-Y " :style='{ height: innerScrollHeight }'>
					<view class="cu-bar solid-bottom">
						<view class="action">
							<text class="cuIcon-titles text-olive"></text><text class="text-gray ">场区信息</text>
						</view>
					</view>

					<form>
						<view class="cu-bar search padding-left-lg padding-right-lg">
							<view class="title padding-left label text-gray">场区名称 <text
									class="margin-xs text-orange">*</text></view>
							<view class="search-form round-sm">
								<!-- <text class="cuIcon-search text-white"></text> -->
								<input class="text-black padding-left" @input="onKeyInput" @focus="InputFocus()"
									@blur="InputBlur()" :adjust-position="false" maxlength="50" type="text"
									placeholder="必填" confirm-type="search" v-model="farmname"></input>
							</view>
						</view>
						<view class="padding-left-lg padding-right-lg">
							<view class="cu-form-group ">
								<view class="title label text-gray">所属组团 <text class="margin-xs text-orange">*</text>
								</view>
								<picker @change="areaPickerChange" :value="areaPickerIdx" :range="areaPickerData">
									<view class="picker">
										{{areaPickerIdx>-1?areaPickerData[areaPickerIdx]:''}}
									</view>
								</picker>
							</view>
						</view>
						<view class="cu-bar search padding-left-lg padding-right-lg">
							<view class="title padding-left label text-gray">排序号 <text
									class="margin-xs text-orange">*</text></view>
							<view class="search-form round-sm">
								<!-- <text class="cuIcon-search text-white"></text> -->
								<input class="text-black padding-left" @input="onKeyInput" @focus="InputFocus()"
									@blur="InputBlur()" :adjust-position="false" maxlength="10" type="number"
									placeholder="" confirm-type="search" v-model="sort"></input>
							</view>
						</view>
						<view class="cu-bar search padding-left-lg padding-right-lg">
							<view class="title padding-left label text-gray">所属省市 <text
									class="margin-xs text-orange">*</text></view>
							<view class="action">
								<view @tap="cityPicker_open()" class=" text-gray padding-right-sm ">{{province}}{{city}}
								</view>
								<view @tap="cityPicker_open()" class="flex justify-right text-xl">
									<text class="cuIcon-location text-olive "></text>
								</view>
							</view>
						</view>

						<view class="cu-bar search padding-left-lg padding-right-lg">
							<view class="title padding-left label text-gray">经纬度 </view>
							<view class="action">
								<view @tap="chooseLocation()" class="text-xs text-gray padding-right-sm ">{{x}}{{y}}
								</view>
								<view @tap="chooseLocation()" class="flex justify-right text-xl">
									<text class="cuIcon-location text-olive "></text>
								</view>
							</view>
						</view>

						<view class="cu-bar search padding-left-lg padding-right-lg">
							<view class="title padding-left label text-gray">联系人 </view>
							<view class="search-form round-sm">
								<!-- <text class="cuIcon-search text-white"></text> -->
								<input class="text-black padding-left" @input="onKeyInput" @focus="InputFocus()"
									@blur="InputBlur()" :adjust-position="false" maxlength="50" type="text"
									placeholder="" confirm-type="search" v-model="person"></input>
							</view>
						</view>

						<view class="cu-bar search padding-left-lg padding-right-lg">
							<view class="title padding-left label text-gray">联系电话 </view>
							<view class="search-form round-sm">
								<!-- <text class="cuIcon-search text-white"></text> -->
								<input class="text-black padding-left" @input="onKeyInput" @focus="InputFocus()"
									@blur="InputBlur()" :adjust-position="false" maxlength="50" type="number"
									placeholder="" confirm-type="search" v-model="phone"></input>
							</view>
						</view>

						<view class="padding-left-lg padding-right-lg padding-top">
							<button @tap="onConfirm" class="cu-btn block bg-blue margin-tb-sm lg round">
								<text class=""></text> 保存</button>
						</view>
						<view class="padding-left-lg padding-right-lg padding-top-xs">
							<button @tap="onDelete" class="cu-btn block line-orange margin-tb-sm lg round">
								<text class=""></text> 删除</button>
						</view>
					</form>

					<cityPicker :column="cityPicker_column" :default-value="cityPicker_defaultValue"
						:mask-close-able="cityPicker_maskCloseAble" @confirm="cityPicker_confirm"
						@cancel="cityPicker_cancel" :visible="cityPicker_visible" />
				</scroll-view>
			</block>

			<block v-if="TabCur==1">
				<view class="cu-bar solid-bottom ">
					<view class="action">
					</view>
					<view class="action">
						<view class="">
							<button v-if="permission_edit" @tap="onAdd()"
								class="cu-btn bg-blue shadow sm margin-right-xxs">新增单元</button>
						</view>
					</view>
				</view>

				<scroll-view scroll-y="true" class="scroll-Y " :style='{ height: houseListScrollHeight }'>
					<view class="house_panel margin-sm" 
						v-for="(item, idx) in houseList" :key="idx" >

						<view class="padding-sm flex align-center">
							<view class="flex-treble text-left">
								<text class="iconfont icon-house  text-gray "></text>
								<text
									class=" text-icon-size text-gray text-md padding-left-xs">{{item.housename}}</text>

							</view>
							<view v-if="permission_edit" class="flex-sub text-right " hover-class="opcity" hover-stay-time="150">
								<i class="iconfont text-gray icon-yingjian  text-lg" style="font-size: 24px;" @tap="onHouseBindClick(item)"></i>
							</view>
							<view v-if="permission_edit" class="flex-sub text-right " hover-class="opcity" hover-stay-time="150">
								<!-- <i class="text-gray cuIcon-edit  text-lg" style="font-size: 24px;"></i> -->
								<uni-icons color="gray"  type="compose" size="30" @tap="onHouseEditClick(item)"></uni-icons>
							</view>
							<view v-if="permission_delete" class="flex-sub text-right " hover-class="opcity" hover-stay-time="150">
								<!-- <uni-icons color="gray" type="minus" size="30" @tap="onHouseDeleteClick(item)"></uni-icons> -->
								<i class="cuIcon-backdelete text-gray text-lg" style="font-size: 24px;" @tap="onHouseDeleteClick(item)"></i>
							</view>
						</view>
					</view>
				</scroll-view>
			</block>
		</scroll-view>
	</view>
</template>

<script>
	import * as api from 'common/api.js';
	import cityPicker from '@/uni_modules/piaoyi-cityPicker/components/piaoyi-cityPicker/piaoyi-cityPicker'
	import {
		API_HEAD
	} from '../../common/api.js';
	export default {
		data() {
			return {
				scrollHeight: 0,
				innerScrollHeight: 0,
				houseListScrollHeight: 0,
				deviceListScrollHeight: 0,
				offsetDeviceListScrollHeight: 0,
				loading: false,

				permission_edit: false,
				permission_delete: false,

				TabCur: 0,

				hasLocation: false,
				location: {},
				locationAddress: '',

				area_id: '',
				id: '',
				farmname: '',
				sort: 0,
				person: '',
				phone: '',
				province: '',
				city: '',
				x: '',
				y: '',
				address: '',

				areaData: [],
				areaPickerData: [],
				areaPickerIdx: 0,

				cityPicker_visible: false,
				cityPicker_maskCloseAble: true,
				cityPicker_str: '',
				cityPicker_defaultValue: '',
				// defaultValue: ['河北省','唐山市','丰南区'],
				cityPicker_column: 2,


				houseList: [],
				house_type: '',
			}
		},
		components: {
			cityPicker
		},
		onReady() {
			// 计算scroll-view高度
			uni.getSystemInfo({
				success: resu => {
					//console.info("窗口高度:", resu.windowHeight)
					const query = uni.createSelectorQuery()
					query.select('.title').boundingClientRect()
					query.exec(res => {

						//console.info("顶部下拉区域:", res[0])
						this.scrollHeight = resu.windowHeight - res[0].height - 10 + 'px';
						this.innerScrollHeight = resu.windowHeight - res[0].height - 10 - 45 + 'px';
						this.houseListScrollHeight = resu.windowHeight - res[0].height - 10 - 45 - 50 +
							'px';
						this.deviceListScrollHeight = resu.windowHeight - res[0].height - 10 - 45;
						//console.log('剩余高度', this.scrollHeight);
					})
				}
			})
		},
		onShow: function() {
			console.info("show farm")
			uni.setNavigationBarTitle({
				title: this.farmname
			});
			this.checkPermission()

			this.loadFarm()
			this.loadHouseList()
		},
		onLoad(option) {
			console.info("load farm", option)
			if (option.farmname) {
				this.farmname = option.farmname
				this.id = option.id
			}
			if (this.id != '') {
				this.loadFarm()
			}
			var that = this
			that.loading = true
			that.loadAreas().then(function(res) {
				that.loading = false
				if (res.code >= 0) {

					var list = res.data
					console.log(list)
					var data = []
					//that.areaPickerData = []
					for (var i = 0; i < list.length; i++) {
						data.push(list[i].group_name + "|" + list[i].name)
					}
					that.areaData = list
					that.areaPickerData = data
					//that.areaPickerIdx = 0
					that.loadFarm()
				}
			});
		},
		methods: {
			onTabSelect(idx) {
				console.info(idx)
				this.TabCur = idx
				if (this.id != '') {

				}
				if (this.id != '') {

				}
				if (this.TabCur == 0) {
					this.loadFarm()
					this.loadHouseList()
				} else if (this.TabCur == 1) {
					this.loadFarm()
					this.loadHouseList()
				}
			},
			InputFocus() {},
			InputBlur() {},
			onKeyInput() {},

			cityPicker_open() {
				this.cityPicker_visible = true
			},
			cityPicker_confirm(val) {
				console.log(val)
				this.cityPicker_str = JSON.stringify(val)
				this.cityPicker_visible = false
				this.province = val.provinceName
				this.city = val.cityName
			},
			cityPicker_cancel() {
				this.cityPicker_visible = false
			},
			chooseLocation: function() {
				uni.chooseLocation({
					success: (res) => {
						console.info(res)
						this.hasLocation = true,
							this.location = formatLocation(res.longitude, res.latitude),
							this.locationAddress = res.address
						console.info(this.location)
						this.x = res.longitude
						this.y = res.latitude
						this.address = res.address
					}
				})
			},
			areaPickerChange: function(e) {
				this.areaPickerIdx = e.detail.value
			},
			checkPermission() {
				var that = this
				that.permission_edit = false
				that.permission_delete = false
				getApp().getActions("/Topo/Tree").then(function(res) {
					if (res.code >= 0) {
						console.info(res.data)
						that.actions = res.data

						for (var i = 0; i < that.actions.length; i++) {
							if (that.actions[i].action_id == 'edit') {
								that.permission_edit = true
							}
							if (that.actions[i].action_id == 'delete') {
								that.permission_delete = true
							}
						}
					} else {
						uni.showToast({
							title: '系统异常，请联系管理员',
							icon: 'none'
						})
					}
				})
			},
			loadAreas() {
				var promise = new Promise(function(resolve, reject) {
					var token = getApp().getToken()
					api.myRequest({
						url: '/Api/Area',
						method: 'GET',
						header: {
							'content-type': 'application/x-www-form-urlencoded',
							'Authorization': 'Bearer ' + token + ''
						},
						data: {},
					}, false).then(res => {
						resolve(res);
					}).catch(err => {
						console.log(err)
						reject(err);
					})
				});
				return promise;
			},
			loadFarm() {
				var that = this
				var token = getApp().getToken()
				api.myRequest({
					url: '/Api/Farm',
					method: 'GET',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'Authorization': 'Bearer ' + token + ''
					},
					data: {
						id: that.id
					},
				}, false).then(res => {
					if (res.code >= 0) {
						console.log(res)
						var items = res.data;
						if (items.length > 0) {
							var obj = items[0]
							that.area_id = obj.area_id
							that.person = obj.person
							that.phone = obj.phone
							that.province = obj.province
							that.city = obj.city
							that.x = obj.x
							that.y = obj.y
							that.sort = obj.sort
							that.address = obj.address

							for (var i = 0; i < that.areaData.length; i++) {
								if (that.areaData[i].id == that.area_id) {
									that.areaPickerIdx = i
									break
								}
							}
						}
					} else {

					}
				}).catch(err => {
					console.log(err)
				})
			},
			onConfirm() {
				this.area_id = this.areaData[this.areaPickerIdx].id
				if (this.area_id == "") {
					uni.showModal({
						title: "数据缺失",
						content: "请选择所属组团",
						showCancel: false,
						confirmText: "确定"
					})
					return
				}
				if (this.farmname == "") {
					uni.showModal({
						title: "数据缺失",
						content: "场区名称不能为空",
						showCancel: false,
						confirmText: "确定"
					})
					return
				}
				if (this.province == "" || this.city == "") {
					uni.showModal({
						title: "数据缺失",
						content: "所属省市不能为空",
						showCancel: false,
						confirmText: "确定"
					})
					return
				}
				var that = this
				uni.showModal({
					title: '提示',
					content: '请注意,本次操作将会被系统记录,是否要继续?',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
							that.saveFarm()
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},

			saveFarm() {
				var that = this
				var token = getApp().getToken()
				that.loading = true
				api.myRequest({
					url: '/Api/Farm',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'Authorization': 'Bearer ' + token + ''
					},
					data: {
						id: that.id,
						area_id: that.area_id,
						farmname: that.farmname,
						sort: that.sort,
						person: that.person,
						phone: that.phone,
						province: that.province,
						city: that.city,
						x: that.x,
						y: that.y,
						address: that.address,
					},
				}, false).then(res => {
					that.loading = false
					if (res.code >= 0) {
						//uni.navigateBack()
						uni.showToast({
							title: '保存成功',
							duration: 2000
						});
					} else {
						uni.showModal({
							title: "错误",
							content: res.msg,
							showCancel: false,
							confirmText: "确定"
						})
					}
				}).catch(err => {
					that.loading = false
					console.log(err)
				})
			},

			onDelete() {
				var that = this
				uni.showModal({
					title: '提示',
					content: '请注意,本次删除将会被系统记录,是否要继续?',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
							that.deleteFarm()
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},

			deleteFarm() {
				var that = this
				var token = getApp().getToken()
				that.loading = true
				api.myRequest({
					url: '/Api/Farm',
					method: 'DELETE',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'Authorization': 'Bearer ' + token + ''
					},
					data: {
						id: that.id,
					},
				}, false).then(res => {
					that.loading = false
					if (res.code >= 0) {
						//
						uni.showToast({
							title: '成功',
							duration: 2000
						});
						uni.navigateBack()
					} else {
						uni.showModal({
							title: "错误",
							content: res.msg,
							showCancel: false,
							confirmText: "确定"
						})
					}
				}).catch(err => {
					that.loading = false
					console.log(err)
				})
			},

			loadHouseList() {
				var that = this
				var token = getApp().getToken()
				that.loading = true
				api.myRequest({
					url: '/Api/House',
					method: 'GET',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'Authorization': 'Bearer ' + token + ''
					},
					data: {
						farmid: that.id
					},
				}, false).then(res => {
					that.loading = false
					if (res.code >= 0) {
						//console.table(res.data)
						var houses = res.data;
						that.houseList = houses
					} else {

					}
				}).catch(err => {
					that.loading = false
					console.log(err)
				})
			},
			onAdd(){
				console.info("onAdd")
				uni.navigateTo({
					url: "/pages/topo/house_edit?id=&housename&farmid="+this.id+"&farmname="+this.farmname
				})
			},
			onHouseEditClick(item){
				uni.navigateTo({
					url: "/pages/topo/house_edit?id=" + item.id +"&housename="+item.housename+"&farmid="+this.id+"&farmname="+this.farmname
				})
			},
			onHouseBindClick(item){
				uni.navigateTo({
					url: "/pages/topo/device_list?id=" + item.id +"&housename="+item.housename
				})
			},
			onHouseDeleteClick(item){
				var that = this
				uni.showModal({
					title: '删除['+item.housename+"]?",
					content: '请注意,本次删除将会被系统记录,是否要继续?',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
							that.deleteHouse(item)
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			deleteHouse(item) {
				var that = this
				var token = getApp().getToken()
				that.loading = true
				api.myRequest({
					url: '/Api/House',
					method: 'DELETE',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'Authorization': 'Bearer ' + token + ''
					},
					data: {
						id: item.id,
					},
				}, false).then(res => {
					that.loading = false
					if (res.code >= 0) {
						//
						uni.showToast({
							title: '成功',
							duration: 2000
						});
						that.loadHouseList()
					} else {
						uni.showModal({
							title: "错误",
							content: res.msg,
							showCancel: false,
							confirmText: "确定"
						})
					}
				}).catch(err => {
					that.loading = false
					console.log(err)
				})
			},
		}
	}
</script>

<style>
	.label {
		width: 120px;
	}

	.round-sm {
		border-radius: 5px;
	}

	.cu-form-group {
		background-color: transparent;
		padding: 0.5px 16px;
		display: flex;
		align-items: center;
		min-height: 55px;
		justify-content: space-between;
		border: 0px;
	}

	.cu-form-group uni-picker .picker {
		color: #333333;
	}

	/* .pupop .popup-box {
	    background: #ff0000 !important;
	} */

	.house_panel {
		min-height: 90rpx;
		border-radius: 5rpx;
		/* background-color: #192654; */
		/* background-color: rgba(100, 100, 100, 0.3); */
		background-color: rgba(230, 230, 230, 0.3);
		box-shadow: 0 2px 4px rgba(100, 100, 155, 0.5);
	}

	.opcity {
		opacity: 0.6;
	}
	
	.split{
		margin: 0 10px;
		border-left: 1px solid #333b51;
	}
</style>